package com.sum.tea.xinlian.viewmodel

import androidx.lifecycle.ViewModel
import com.sum.tea.contants.AppConfig
import com.uhf.api.cls.Reader
import java.io.File
import java.io.FileOutputStream
import java.io.IOException
import kotlin.experimental.and

class SubSystemViewModel : ViewModel() {
    lateinit var app: AppConfig
    val strThMode = arrayOf("MainActivity_thread", "event_broast")

    fun initialize(appConfig: AppConfig) {
        app = appConfig
    }

    fun setDefaultParams() {
        app.Rparams.apply {
            opant = 1
            invpro = arrayListOf("GEN2")
            opro = "GEN2"
            uants = intArrayOf(1)
            readtime = 50
            sleep = 0
            checkant = 1
            crpow.let {
                rpow = IntArray(16) { it }
                wpow = IntArray(16) { it }
            }
            region = 1
            frelen = 0
            session = 0
            qv = -1
            wmode = 0
            blf = 0
            maxlen = 0
            target = 0
            gen2code = 2
            gen2tari = 0
            fildata = ""
            filadr = 32
            filbank = 1
            filisinver = 0
            filenable = 0
            emdadr = 0
            emdbytec = 0
            emdbank = 1
            emdenable = 0
            adataq = 0
            rhssi = 1
            invw = 0
            iso6bdeep = 0
            iso6bdel = 0
            iso6bblf = 0
        }
        app.spf.SaveReaderParams(app.Rparams)
    }

    fun setThreadMode(threadMode: Int) {
        app.ThreadMODE = threadMode
    }

    suspend fun exportTagData(filePath: String): String? {
        return try {
            FileOutputStream(File(filePath)).use { fs ->
                val wstr = "EPC,Count,Ant,Rssi,Fre,Res,Time,Emd\r\n"
                fs.write(wstr.toByteArray())
                app.TagsMap.forEach { (_, tagInfo) ->
                    val linestr = StringBuilder().apply {
                        append(Reader.bytes_Hexstr(tagInfo.EpcId)).append(",")
                        append(tagInfo.ReadCnt).append(",")
                        append(tagInfo.AntennaID).append(",")
                        append(tagInfo.RSSI).append(",")
                        append(tagInfo.Frequency).append(",")
                        append(tagInfo.Res[1] and 0x3F).append(",")
                        append(tagInfo.TimeStamp).append(",")
                        if (tagInfo.EmbededDatalen > 0) append(Reader.bytes_Hexstr(tagInfo.EmbededData)).append(",")
                        append("\r\n")
                    }.toString()
                    fs.write(linestr.toByteArray())
                }
            }
            AppConfig.Constr_subsysaveok
        } catch (e: IOException) {
            e.printStackTrace()
            null
        }
    }
}
